<?php

namespace App\Http\Controllers\Client;

use App\Model\Comment;
use App\Services\Util;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class CommentController extends ClientController
{
    public function add()
    {
        $comment = new Comment();
        $rules = [
            'content' => 'required',
            'author'  => 'required',
            'post_id' => 'required',
        ];
        $validator = Validator::make(Input::all(), $rules);
        if ($validator->fails()) {
            return self::apiFail("参数错误");
        }
        $post_id = Input::get('post_id');
        $parent  = Input::get('parent');
        if(empty($parent)){
            $parent = Comment::ROOT_COMMENT;
            $level  = Comment::ROOT_LEVEL;
        }else{
            $last_comment = Comment::where('id',$parent)->first();
            if(empty($last_comment)||$post_id != $last_comment->post_id)
            {
                return self::apiFail('参数错误');
            }
            $level = (int)$last_comment->level + 1;
        }
        $comment_ip = $this->request->getClientIp();
        $content = Util::trimAll(Input::get('content'));
        $comment->author  = Input::get('author');
        $comment->name    = Input::get('name');
        $comment->post_id = $post_id;
        $comment->content = $content;
        $comment->parent  = $parent;
        $comment->level   = $level;
        $comment->comment_ip = $comment_ip;
        $comment->save();
        return self::apiSucc('评论成功');
    }
}
